package com.jqsoft.launcher.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.login.BphsLoginActivity;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.AndroidUtil;
import com.jqsoft.launcher.util.Log;

import org.apache.commons.lang.StringUtils;

/**所有activity界面的基类
 * @author gujunqi jqkj5350880
 * date：2013-12-24 
 */
public abstract class JQActivity extends Activity {
	private final String tag = this.getClass().getName();// "YTActivity";

	public static final int FINISH_ACTIVITY_MSG_ID=0;
	protected JQActivity act;
	protected Context ctx;
	private ProgressDialog progressBar; // 等待层.....
	protected UserLoginInfo userLoginInfo = UserLoginInfo.getInstances();

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ctx = act = this;
		Log.i("JQActivity", "进入onCreate");
		// VMRuntime.getRuntime().setTargetHeapUtilization(SPDBConstants.TARGET_HEAP_UTILIZATION);
		// 设置最小heap内存 大小。 这段代码在部分机器上会导致崩溃(G7 X10)
		// VMRuntime.getRuntime().setMinimumHeapSize(SPDBConstants.TARGET_HEAP_UTILIZATION);
		
		if (getContentLayout() != 0) {
			setContentView(getContentLayout());
		}
		initGui();
		initAction();
		initData();
	}
	protected abstract int getContentLayout();
	
	/**
	 * 初始化UI
	 */
	protected abstract void initGui();

	/**
	 * 初始化事件
	 */
	protected abstract void initAction();

	/**
	 * 初始化数据
	 */
	protected abstract void initData();
	
	/**
	 * 根据资源id获取值
	 */
	protected String getResString(int resId) {
		return act.getResources().getString(resId);
	}
	
	public void onStart() {
		super.onStart();
		Log.i("JQActivity", "进入onStart");
	}

	public void onRestart() {
		super.onRestart();
		Log.i("JQActivity", "进入onRestart");
	}

	protected void onResume() {
		super.onResume();
		Log.i("JQActivity", "进入onResume");
	}

	protected void onPause() {
		super.onPause();
		Log.i("JQActivity", "进入onPause()");
	}

	public void onStop() {
		super.onStop();
		Log.i("JQActivity", "进入onStop");
	}
	
	public void onDestroy() {
		super.onDestroy();
		if (progressBar != null && progressBar.isShowing()) {
			progressBar.dismiss();
		}
		
		Log.i("JQActivity", "进入onDestroy");
	}
	
	
	/**
	 * 关闭等待层
	 */
	public void dismissrogressBar() {
		Log.i(tag, "取消等待层....");
		if (progressBar != null && progressBar.isShowing()) {
			progressBar.dismiss();
			progressBar=null;
		}
	}
//等待层 没有提示的
	protected void loadWaitPanel() {
		loadWaitPanel(null);
	}

	protected void loadWaitPanel(String message) {
		loadWaitPanelAutoClose(message, false);
	}


	protected void loadWaitPanelMain(String message) {
		loadWaitPanelAutoClose(message, true);
	}

//	等待层可以自动关闭  可以设置等待层不可以返回关闭
	public void loadWaitPanelAutoClose(String message, boolean isCancelable) {
		ctx = act;
		if(progressBar != null){
			return;
		}
		progressBar = new ProgressDialog(ctx);
		progressBar.setCancelable(isCancelable);
		progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		if (StringUtils.isBlank(message)) {
			progressBar.setMessage("正在加载,请稍候......");
		} else {
			progressBar.setMessage(message);
		}
		progressBar.setIndeterminate(false);
		progressBar.show();

		// 防止程序长时间等待，50秒后，关闭等待层
		new Thread() {
			public void run() {
				try {
					Thread.sleep(Constant.CLOSE_WAIT_PANEL_MILLISECOND);
					Log.d(tag, "线程关闭等待层closeWaitPanel.");
				} catch (Exception e) {
				}
				mHandler.sendEmptyMessage(FINISH_ACTIVITY_MSG_ID);
			}
		}.start();
	}

//	等待层不可以自动关闭  
	public void loadWaitPanelNoAutoClose(String message, boolean isCancelable) {
		ctx = act;
		progressBar = new ProgressDialog(ctx);
		progressBar.setCancelable(isCancelable);
		progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		if (StringUtils.isBlank(message)) {
			progressBar.setMessage("正在加载,请稍候......");
		} else {
			progressBar.setMessage(message);
		}
		progressBar.setIndeterminate(false);
		progressBar.show();
	}

	private final Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int what = msg.what;
			if (what == FINISH_ACTIVITY_MSG_ID){
				//chenxu     comment next line to prevent destroy unexpectedly
//				onDestroy();
				dismissrogressBar();
			}
		}
	};

	
	protected OnClickListener leftlistener = new OnClickListener() {
		public void onClick(View v) {
			act.setResult(Constant.GO_BACK);
			act.finish();
			overridePendingTransition(android.R.anim.slide_in_left,
					android.R.anim.slide_out_right);
		}
	};

	public void setGoBack(){
		Button title_bar_left_button=(Button) findViewById(R.id.title_bar_left_button);
		title_bar_left_button.setOnClickListener(leftlistener);
	}
	

	public void setGoBack_Gone(){
		Button title_bar_left_button=(Button) findViewById(R.id.title_bar_left_button);
		title_bar_left_button.setVisibility(View.GONE);
	}
//	public void execute() {
//		act.finish();
//		JQActivity.super.overridePendingTransition(
//				android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//		Constant.IS_EXIT = false;
//	}

	// ---------------------屏蔽 home,back,menu键----------------------------
	public void onAttachedToWindow() {
		//注释掉下一行来避免应用崩溃	chenxu
//		act.getWindow()
//				.setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		super.onAttachedToWindow();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.d(tag, "BACK键捕获。to BACK");
//			if(!(act instanceof SplashActivitys|| act instanceof BphsLoginActivity)){
			act.finish();
			act.overridePendingTransition(android.R.anim.slide_in_left,
					android.R.anim.slide_out_right);
			return true;
//			}
		}
		if (KeyEvent.KEYCODE_HOME == keyCode) {
			Log.d(tag, "home键捕获。to home");
			if(!(act instanceof SplashActivitys || act instanceof BphsLoginActivity)){
			toHome();
			return true;		}
		}
		return true;
//		return super.onKeyDown(keyCode, event);
	}


	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, R.string.exit);// 组,item,order,content
		menu.add(0, 2, 2, R.string.cancel);// 组,item,order,content
		// menu.setQwertyMode(true);
		return super.onCreateOptionsMenu(menu);
	}


	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
		case 1:// 
			act.finish();
			act.overridePendingTransition(0, 0);
			exitSystem();
			break;
		// case 2: // 
		// finish();
		// // overridePendingTransition(0, 0);
		// break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void exitSystem() {
		userLoginInfo.clean();
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		manager.restartPackage(getPackageName());
		android.os.Process.killProcess(android.os.Process.myPid());
		System.gc();
		System.exit(0);
		
		Intent intent = new Intent(act, ExitSystemActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		// overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
		
	}

	/**
	 * 关闭除当前应用外的应用
	 */
//	protected void closeExtraApp() {
//		List<Activity> activityList = MainItemActivity.activityList;
//		int length = activityList.size();
//		for (int i = 0; i < length; i++) {
//			Activity activity = activityList.get(i);
//			if (null != activity) {
//				activity.finish();
//			}
//		}
//	}


	public void overridePendingTransition(int enterAnim, int exitAnim) {
		if (AndroidUtil.oSVersionIsLow2Version(act)) {
			super.overridePendingTransition(0, 0);
			return;
		}
		if (0 == enterAnim && 0 == exitAnim) {
			super.overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
		} else {
			super.overridePendingTransition(enterAnim, exitAnim);
		}
	}
	
//	设置标题
	public void setTitle(String titleStr) {
		Button title_bar_title_textview=(Button) findViewById(R.id.title_bar_title_textview);
		title_bar_title_textview.setText(titleStr);
	}
	
	
//跳到主界面
	public void toHome() {
		Intent intent = new Intent(act, MainFunctionActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		// overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
	}
	
//	默认是需要关闭
	public void to( Class<?>  cls) {
		to(cls, true);
	}

	public void toNoFinish( Class<?>  cls) {
		to(cls, false);
	}

	protected void to( Class<?>  cls, 
			boolean isFinish) {
		Intent intent = new Intent(act,cls);  
		startActivity(intent);
		if(isFinish){
			 act.finish();
		}
		overridePendingTransition(0, 0);
	}
}
